package com.openwater;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;

public class AppListActivity extends Activity {

    private String TAG = "appList";
    private ListView mListView = null;
    private List<AppInfo> mAppInfos = null;
    private List<AppInfo> mPickApps = new ArrayList<AppListActivity.AppInfo>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.applist_view);
        new Thread(new Runnable() {
            @Override
            public void run() {
                mAppInfos = getAppInfo();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                        findViewById(R.id.progressBar1).setVisibility(View.GONE);
                        findViewById(R.id.layer02).setVisibility(View.VISIBLE);
                    }
                });
            }
        }).start();
        mListView = (ListView) findViewById(R.id.listview_apps);
        mListView.setAdapter(mAdapter);
        findViewById(R.id.btn_addapp).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                for (AppInfo appInfo : mPickApps) {
                    Log.d(TAG, appInfo.toString());
                }
            }
        });
    }

    public List<AppInfo> getPickedInfos() {
        return mPickApps;
    }

    private OnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            AppInfo appInfo = mAppInfos.get(buttonView.getId());
            if (isChecked && !mPickApps.contains(appInfo)) {
                Log.d(TAG, "add:" + appInfo.toString());
                mPickApps.add(appInfo);
            } else if (!isChecked && mPickApps.contains(appInfo)) {
                Log.d(TAG, "remove:" + appInfo.toString());
                mPickApps.remove(appInfo);
            }
        }
    };

    private BaseAdapter mAdapter = new BaseAdapter() {
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).inflate(
                        R.layout.applist_view_item, null);
                final ViewHolder holder = new ViewHolder();
                holder.appName = (TextView) convertView.findViewById(R.id.textview_app_name);
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
                holder.checkBox.setOnCheckedChangeListener(mOnCheckedChangeListener);
                convertView.setTag(holder);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            AppInfo appInfo = mAppInfos == null ? null : mAppInfos.get(position);
            if (mListView != null && holder != null && appInfo != null) {
                Drawable drawable = appInfo.getDrawable();
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                holder.appName.setText(appInfo.getName());
                holder.appName.setCompoundDrawables(drawable, null, null, null);
                holder.checkBox.setId(position);
                if (mPickApps.contains(appInfo)) {
                    holder.checkBox.setChecked(true);
                } else {
                    holder.checkBox.setChecked(false);
                }
            }
            return convertView;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public int getCount() {
            return mAppInfos == null ? 0 : mAppInfos.size();
        }
    };

    private class ViewHolder {
        private TextView appName;
        private CheckBox checkBox;
    }

    public static class AppInfo {

        private String name;
        private String version;
        private Drawable drawable;
        private boolean isUserApp;
        private String packageName;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }

        public Drawable getDrawable() {
            return drawable;
        }

        public void setDrawable(Drawable drawable) {
            this.drawable = drawable;
        }

        public boolean isUserApp() {
            return isUserApp;
        }

        public void setUserApp(boolean isUserApp) {
            this.isUserApp = isUserApp;
        }

        public String getPackageName() {
            return packageName;
        }

        public void setPackageName(String packageName) {
            this.packageName = packageName;
        }

        @Override
        public String toString() {
            return "AppInfo [name=" + name + ", version=" + version + ", isUserApp=" + isUserApp
                    + ", packageName=" + packageName + "]";
        }

    }

    public List<AppInfo> getAppInfo() {
        PackageManager pm = getApplicationContext().getPackageManager();
        List<PackageInfo> pakageinfos = pm
                .getInstalledPackages(PackageManager.GET_ACTIVITIES);
        List<AppInfo> appInfos = new ArrayList<AppInfo>();
        for (PackageInfo packageInfo : pakageinfos) {
            AppInfo appInfo = new AppInfo();
            String str_name = packageInfo.applicationInfo.loadLabel(pm).toString();
            appInfo.setName(str_name);
            String version = packageInfo.versionName;
            appInfo.setVersion(version);
            Drawable drawable = packageInfo.applicationInfo.loadIcon(pm);
            appInfo.setDrawable(drawable);
            appInfo.setUserApp(filterSystemApp(packageInfo.applicationInfo));
            appInfo.setPackageName(packageInfo.packageName);
            appInfos.add(appInfo);
            Log.i("appinfo", "version : " + version + " app name:" + str_name);
        }
        return appInfos;
    }

    /**
     * 
     * @param info
     * @return true if APP is user APP but false is system APP
     */
    public boolean filterSystemApp(ApplicationInfo info) {
        return ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)
                || ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0);
    }
}
